<?php

namespace App\Http\Resources\SiteLocation;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\UploadFileResourceEnum;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Http\Resources\BaseResource;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUploadFileResourceModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationWangguiRelationModel;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\OpenShop\Wap\SignOrderService;
use App\Service\Rms\ShopService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class ClueSiteLocationResource extends BaseResource
{
    public static ?Collection $rmsUser = null;

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        $placeholderTime       = $this->placeholderTime ? date('Y-m-d H:i:s', $this->placeholderTime) : '';
        $nearbyPlaceHolderName = OpenShopSiteLocationModel::getShopNameByIdNearByPlaceholderId($this->nearbyPlaceHolderId);
        $relationWangguiModel  = OpenShopSiteLocationWangguiRelationModel::query()->where('siteId', $this->id)->first();
        $getWgName             = OpenShopSiteLocationWangguiRelationModel::getWgName($relationWangguiModel);
        $lng                   = $this->longitude;
        $lat                   = $this->latitude;
        return array_merge([
            "id"              => $this->id,
            "orderNo"         => $this->orderNo,
            "clueStatus"      => $this->clueStatus,
            "clueStatusText"  => OpenShopSiteLocationModel::CLUE_STATUS_MAP[$this->clueStatus],
            "refereeUsername" => $this->getRefereeUsername(),
            "cityArea"        => $this->cityArea,
            "address"         => $this->address,
            "leaseMobile"     => $this->leaseMobile,
            "leaseName"       => $this->leaseName,
            "area"            => $this->area,
            "siteAddress"     => $this->siteAddress,
            "clueRent"        => $this->fixedRent,
            "fixedRent"       => $this->fixedRent,
            "rentType"        => $this->rentType,
            "remind"          => $this->remind,
            "rentPaymentCycle" => $this->rentPaymentCycle,
            "rentFreePeriod"  => $this->rentFreePeriod,
            "deposit"         => $this->deposit,
            'image'           => "https://restapi.amap.com/v3/staticmap?location={$lng},{$lat}&markers=-1,https://file.51kuafu.com/e0/0c/cc0783d7de4fd65c070c14510370bf7dd73969cf2cf804cfe797d5dd23cd.png,0:{$lng},{$lat}&zoom=16&size=646*204&key=" . WangGuiCityByPower::getRandomAmapKey(),
            "messageFrom"     => $this->messageFrom,
            "shopModelType"   => $this->shopModelType,
            "cityType"        => $this->cityType,
            "nearbyRange"     => $this->nearbyRange,
            "longitude"       => $this->longitude,
            "latitude"        => $this->latitude,
            "provinceCode"    => $this->provinceCode,
            "cityCode"        => $this->cityCode,
            "areaCode"        => $this->areaCode,
            "nearbyShopCode"  => $this->nearbyShopCode,
            'mallName'        => $this->mallName,
            'mallId'          => $this->mallId,
            'isWhiteList'     => $this->isWhiteList,
            'mallGrade'       => $this->mallGrade,
            'mallStatus'      => $this->mallStatus,
            'nearbyPlaceHolderRange' => $this->nearbyPlaceHolderRange,
            'nearbyPlaceHolderId'    => $this->nearbyPlaceHolderId,
            'nearbyPlaceHolderName'  => ($nearbyPlaceHolderName ?? '') ?: '该城市内无预占点位',
            'nearbyPlaceholderTime'  => $placeholderTime,
            'town'                   => $this->town,
            'townGrade'              => $this->townGrade,
            'townText'               => $this->town . ($this->townGrade > 0 ? ('（' . ProgrammingEnum::GRADE_MAPPING[$this->townGrade]  . ')') : ''),
            'wgName'                 => $getWgName,
            'wgMatch'                => (int)optional($relationWangguiModel)->match,
            'wgNumber'               => (string)optional($relationWangguiModel)->wgNumber,
            'wgMatchStr'             => OpenShopSiteLocationWangguiRelationModel::MATCH_MAPPING[optional($relationWangguiModel)->match] ?? '',
            'wgGradeValue'           => (int)optional($relationWangguiModel)->grade,
            'wgGrade'                => (int)optional($relationWangguiModel)->grade ? (ProgrammingEnum::GRADE_MAPPING[(int)optional($relationWangguiModel)->grade] ?? '') : '',
            'shopType'               => $this->shopType,// 店型
            'siteSelection'          => $this->siteSelection,// 选址场景
            'recommendType'          => $this->recommendType,// 铺位推荐方式
        ], $this->getAttachInfo(), $this->getNearbyShopNameByShopCode());
    }

    /**
     * @return array
     */
    public function getAttachInfo(): array
    {
        return $this->attachRel->groupBy("position")->map(function ($v, $k) {
            return [
                "key" => UploadFileResourceEnum::CLUE_SITE_LOCATION_MAP[$k],
                "url" => $v->map(function ($v) {
                    if ($v->isPublic == 1) {
                        $v->url = picturePath($v->url);
                    } else {
                        $v->url = privateFilePath($v->url);
                    }
                    return $v;
                })->pluck("url")->values()->toArray()
            ];
        })->values()->pluck("url", "key")->toArray();
    }

    public function getRefereeUsername()
    {
        $userInfo = empty($this->createdByUid) || empty(self::$rmsUser) || !self::$rmsUser->offsetExists($this->createdByUid) ?
            null : self::$rmsUser->get($this->createdByUid);
        return $userInfo ? $userInfo['username'] : '';
    }

    private function getNearbyShopNameByShopCode()
    {
        $nearbyShopName = ShopService::getShopNameByCode($this->nearbyShopCode);
        // try {
        //     $shopInfo = $this->nearbyShopCode ? (GuanyuanDataService::newShopList($this->nearbyShopCode)[0] ?? []) : [];
        // } catch (\Exception $exception) {
        //     $shopInfo = [];
        // }
        //
        // if (!empty($shopInfo)) $nearbyShopName = '【' . ($shopInfo['状态'] ?? '-') . '】'. ($shopInfo['门店名称'] ?? '-');
        return ['nearbyShopName' => $nearbyShopName ? ($this->nearbyShopCode . $nearbyShopName): '该城市内无夸父门店'];
    }
}
